package com.zoe.thread.th09_readwrite读写锁;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @Author Zoe
 * @Date: 2021/05/04
 * @Description 读写锁
 * <p>
 * 总结：读-读    可以共存
 * 读-写    不可以共存
 * 写-写    不可以共存
 */

class MyCache {
    private volatile Map<String, Object> hashMap = new HashMap();
    private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    public void put(String key, Object value) {
        readWriteLock.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + "开始写入：" + key);
            TimeUnit.MILLISECONDS.sleep(300);
            hashMap.put(key, value);
            System.out.println(Thread.currentThread().getName() + "写入完成");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            readWriteLock.writeLock().unlock();
        }


    }

    public void get(String key) {
        readWriteLock.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + "开始读取：" + key);
            TimeUnit.MILLISECONDS.sleep(300);
            hashMap.get(key);
            System.out.println(Thread.currentThread().getName() + "读取完成-----" + hashMap.get(key));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            readWriteLock.readLock().unlock();
        }
    }
}

public class ReadWriteLockDemo {
    public static void main(String[] args) throws InterruptedException {
        MyCache myCache = new MyCache();

        // 写操作
        for (int i = 0; i < 5; i++) {
            final int temInt = i;
            new Thread(() -> {
                myCache.put(temInt + "", temInt + "");

            }, i + "").start();
        }

        // 读操作
        for (int i = 0; i < 5; i++) {
            final int temInt = i;
            new Thread(() -> {
                myCache.get(temInt + "");
            }, i + "=").start();
        }

    }
}
